package mamikeji.liaowa.ui.activity.right;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.model.IPickerViewData;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.UpdateWaBean;
import mamikeji.liaowa.bean.Wa_BabyMSG_Bean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.activity.right.update.UpdateWaJieshaoActivity;
import mamikeji.liaowa.ui.activity.right.update.UpdateWaNameActivity;
import mamikeji.liaowa.utils.FileUtils;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.utils.XingZuo;
import mamikeji.liaowa.widget.selectorImage.MultiImageSelector;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnCompressListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UpdateWaMSGActiity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "UpdateWaMSGActiity";
    private static final int REQUEST_CAMERA = 100;
    private static final int REQUEST_GALLERY = 101;
    private static final int RESULT_REQUEST_CODE = 102;
    @BindView(R.id.textView_wa_msg_name)
    public TextView textView_wa_msg_name;
    @BindView(R.id.textView_wa_msg_sex)
    public TextView textView_wa_msg_sex;
    @BindView(R.id.textView_wa_msg_birthday)
    public TextView textView_wa_msg_birthday;
    @BindView(R.id.textView_wa_msg_xingzuo)
    public TextView textView_wa_msg_xingzuo;
    @BindView(R.id.textView_wa_msg_height)
    public TextView textView_wa_msg_height;
    @BindView(R.id.textView_wa_msg_weight)
    public TextView textView_wa_msg_weight;
    @BindView(R.id.textView_wa_msg_jianjie)
    public TextView textView_wa_msg_jianjie;
    @BindView(R.id.imageView_wa_msg_header_titleimg_sel)
    public SimpleDraweeView imageView_wa_msg_header_titleimg_sel;
    @BindView(R.id.multiStateView_wa_msg_update)
    public MultiStateView multiStateView_wa_msg_update;

    @BindView(R.id.relativeLayout_wa_nickname)
    RelativeLayout relativeLayoutWaNickname;
    @BindView(R.id.relativeLayout_wa_sex)
    RelativeLayout relativeLayoutWaSex;
    @BindView(R.id.relativeLayout_wa_birthday)
    RelativeLayout relativeLayoutWaBirthday;
    @BindView(R.id.relativeLayout_wa_xingzuo)
    RelativeLayout relativeLayoutWaXingzuo;
    @BindView(R.id.relativeLayout_wa_height)
    RelativeLayout relativeLayoutWaHeight;
    @BindView(R.id.relativeLayout_wa_weight)
    RelativeLayout relativeLayoutWaWeight;
    @BindView(R.id.relativeLayout_wa_jieshao)
    RelativeLayout relativeLayoutWaJieshao;
    @BindView(R.id.textView_user_msg_birthday)
    TextView textViewUserMsgBirthday;

    String babyID;

    private Dialog dialog_camera;

    private ArrayList<CardBean> cardSexItem = new ArrayList<>();
    private ArrayList<CardBean> cardWeightItem = new ArrayList<>();
    private ArrayList<CardBean> cardHeightItem = new ArrayList<>();
    private OptionsPickerView pvCustomOptions_sex, pvCustomOptions_weight, pvCustomOptions_height;

    //时间选择器
    TimePickerView pvTime;

    private String mImageFileName;

    private Wa_BabyMSG_Bean wa_babyMSG_bean;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    ForPreference.putString(ForContents.WA_headerimg_url, (String) msg.obj);
                    imageView_wa_msg_header_titleimg_sel.setImageURI(Uri.parse((String) msg.obj));
                    ForToast.showToast("修改成功！");
                    hideLoading();
                    break;
                case 1:
                    ForToast.showToast("修改失败！");
                    hideLoading();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_wa_msg);
        getBase();
        ButterKnife.bind(this);
        setTitleLeftImage(R.drawable.icon_fanhuibai_n_fff, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ForPreference.getBoolean(ForContents.WA_BIRTHDAY_BOOL)) {
                    setResult(RESULT_OK, new Intent());
                }
                finish();
            }
        });
        setTitleName(R.string.wa_msg_update_name);
        babyID = getIntent().getStringExtra("babyID");

        multiStateView_wa_msg_update.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateView_wa_msg_update.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        getBabyDate();
                    }
                });

        getBabyDate();
        userimg_dig();
        initSexPicker();
        initWeightPicker();
        initHeightPicker();
    }

    private void getBabyDate() {
        Map<String, String> formMap = new HashMap<>();
        formMap.put(HttpKey.WA_DATE_ID, babyID);
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.USERBADY_DATE, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateView_wa_msg_update.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        wa_babyMSG_bean = new Gson().fromJson(response, Wa_BabyMSG_Bean.class);
                        if (wa_babyMSG_bean.getUserBaby() != null) {
                            //设置时间范围
                            time_data(wa_babyMSG_bean.getUserBaby().getStatus() == 2);

                            relativeLayoutWaHeight.setVisibility(wa_babyMSG_bean.getUserBaby().getStatus() == 2 ? View.VISIBLE : View.GONE);
                            relativeLayoutWaWeight.setVisibility(wa_babyMSG_bean.getUserBaby().getStatus() == 2 ? View.VISIBLE : View.GONE);

                            imageView_wa_msg_header_titleimg_sel.setImageURI(Uri.parse(wa_babyMSG_bean.getUserBaby().getAvatar()));
                            String newStr = wa_babyMSG_bean.getUserBaby().getBirthtime()
                                    .substring(6, wa_babyMSG_bean.getUserBaby().getBirthtime().length() - 2);
                            Long datatime = Long.valueOf(newStr);
                            textView_wa_msg_birthday.setText(getFormatedDateTime("yyyy-MM-dd", datatime));
                            textView_wa_msg_height.setText(wa_babyMSG_bean.getUserBaby().getHeight() + "cm");
                            textView_wa_msg_weight.setText(wa_babyMSG_bean.getUserBaby().getWeight() + "kg");
                            textView_wa_msg_xingzuo.setText(wa_babyMSG_bean.getUserBaby().getConstellation());
                            textView_wa_msg_sex.setText(wa_babyMSG_bean.getUserBaby().getSex().equals("1") ? "男" : "女");

                            ForPreference.putString(ForContents.WA_nickname, wa_babyMSG_bean.getUserBaby().getNickName());
                            ForPreference.putString(ForContents.WA_describe, wa_babyMSG_bean.getUserBaby().getDescribe());

                            textView_wa_msg_name.setText(ForPreference.getString(ForContents.WA_nickname));
                            textView_wa_msg_jianjie.setText(ForPreference.getString(ForContents.WA_describe));

                            textViewUserMsgBirthday.setText(wa_babyMSG_bean.getUserBaby().getStatus() == 2 ? "生日" : "预产期");

                            multiStateView_wa_msg_update.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            multiStateView_wa_msg_update.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    } else {
                        multiStateView_wa_msg_update.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static String getFormatedDateTime(String dateFormat, long dateTime) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(dateFormat);
        return sDateFormat.format(new Date(dateTime + 0));
    }

    private Button btn_userimg_camera, btn_userimg_album, btn_userimg_cancel;

    @OnClick({
            R.id.imageView_wa_msg_header_titleimg_sel,
            R.id.relativeLayout_wa_nickname,
            R.id.relativeLayout_wa_sex,
            R.id.relativeLayout_wa_birthday,
            R.id.relativeLayout_wa_xingzuo,
            R.id.relativeLayout_wa_height,
            R.id.relativeLayout_wa_weight,
            R.id.relativeLayout_wa_jieshao
    })
    @Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.imageView_wa_msg_header_titleimg_sel:
                dialog_camera.show();
                break;
            case R.id.btn_userimg_camera:
                dialog_camera.hide();
                photo();
                break;
            case R.id.btn_userimg_album:
                dialog_camera.hide();
                MultiImageSelector.create(this)
                        .showCamera(false) // 是否显示相机. 默认为显示
                        .count(1) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                        .single() //单选
                        .start(this, REQUEST_GALLERY);
                break;
            case R.id.btn_userimg_cancel:
                dialog_camera.hide();
                break;
            case R.id.relativeLayout_wa_nickname:
                intent = new Intent(UpdateWaMSGActiity.this, UpdateWaNameActivity.class);
                intent.putExtra(ForContents.WA_ID, babyID);
                intent.putExtra(ForContents.WA_nickname, wa_babyMSG_bean.getUserBaby().getNickName());
                startActivity(intent);
                break;
            case R.id.relativeLayout_wa_sex:
                pvCustomOptions_sex.show();
                break;
            case R.id.relativeLayout_wa_birthday:
                pvTime.show();
                break;
            case R.id.relativeLayout_wa_height:
                pvCustomOptions_height.show();
                break;
            case R.id.relativeLayout_wa_weight:
                pvCustomOptions_weight.show();
                break;
            case R.id.relativeLayout_wa_jieshao:
                intent = new Intent(UpdateWaMSGActiity.this, UpdateWaJieshaoActivity.class);
                intent.putExtra(ForContents.WA_ID, babyID);
                intent.putExtra(ForContents.WA_describe, wa_babyMSG_bean.getUserBaby().getDescribe());
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_GALLERY) {
                List<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                if (mSelectPath != null && mSelectPath.size() > 0) {
                    Uri uri = Uri.fromFile(new File(mSelectPath.get(0)));
                    startPhotoZoom(uri);
                }
            } else if (requestCode == REQUEST_CAMERA) {
                File file = new File(Environment.getExternalStorageDirectory() + "/" + mImageFileName);
                Uri uri = Uri.fromFile(file);
                startPhotoZoom(uri);
            } else if (requestCode == RESULT_REQUEST_CODE) {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap bitmap = extras.getParcelable("data");
                    FileUtils.saveBitmap(bitmap, "avatar");
                    File file = new File(FileUtils.SDPATH + "avatar.jpg");
                    if (file != null) {
                        compress(file);
                    }
                }
            }
        }
    }

    private void compress(File f) {
        Luban.compress(this, f)
                .putGear(Luban.CUSTOM_GEAR)
                .setMaxSize(300)
                .launch(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        uploadImage(file);
                    }

                    @Override
                    public void onError(Throwable e) {
                        ForToast.showToast("压缩失败");
                        ForLog.i("compresscompresscompress", "" + e.toString());
                    }
                });
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 340);
        intent.putExtra("outputY", 340);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    public void photo() {
        // 随机缓存照片名
        mImageFileName = FileUtils.getFileNameForSystemTime(".jpg");
        // 首先判断SD卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), mImageFileName)));
            startActivityForResult(intent, REQUEST_CAMERA);
        } else {
            ForToast.showToast("内存卡不存在");
        }
    }

    private void uploadImage(File file) {
        showLoading();
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("file", "file.jpg", RequestBody.create(MultipartBody.FORM, file));
        builder.addFormDataPart("id", babyID);
        MultipartBody body = builder.build();

        OkHttpClient okHttpClient = new OkHttpClient();
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(HttpApi.ROOT_PATH + HttpApi.UPLOAD_BABY_IMG)
                .post(body)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("失败:" + e.toString());
                hideLoading();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                ForLog.i("json_json", json + "");
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    String status = jsonObject.getString(HttpKey.STATUS);

                    Message message = Message.obtain();

                    if ("200".equals(status)) {
                        UpdateWaBean updateWaBean = new Gson().fromJson(json, UpdateWaBean.class);
                        message.what = 0;
                        message.obj = updateWaBean.getBadyuser().getAvatar();
                        handler.sendMessage(message);
                        ForPreference.putString(ForContents.WA_HeaderImg, updateWaBean.getBadyuser().getAvatar());
                    } else {
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //出生日期
    public void time_data(boolean bool_state) {
        Calendar startDate, endDate;
        if (bool_state) {
            //已出生
            int endY = 0;
            int years = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
            int months = Integer.parseInt(new SimpleDateFormat("MM").format(new Date()));
            int days = Integer.parseInt(new SimpleDateFormat("dd").format(new Date()));

            endY = years - 6;
            months = months - 1;

            startDate = Calendar.getInstance();
            startDate.set(endY, months, days);
            endDate = Calendar.getInstance();
            endDate.set(years, months, days);
        } else {
            //预产期
            int years = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
            int months = Integer.parseInt(new SimpleDateFormat("MM").format(new Date()));
            int days = Integer.parseInt(new SimpleDateFormat("dd").format(new Date()));

            int endY = years + 1;

            startDate = Calendar.getInstance();
            startDate.set(years, months - 1, days);
            endDate = Calendar.getInstance();
            endDate.set(endY, months - 1, days);
        }

        boolean[] booleen = new boolean[]{true, true, true, false, false, false};
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                getUpdateBirthday(getTime(date));
            }
        })
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setType(booleen)//默认全部显示
                .setLabel("", "", "", "", "", "")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
    }

    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    //拍照弹框
    public void userimg_dig() {
        dialog_camera = new Dialog(UpdateWaMSGActiity.this, R.style.ActionSheetDialogStyle);
        View inflate = LayoutInflater.from(UpdateWaMSGActiity.this).inflate(R.layout.dialog_usermsg_img, null);

        btn_userimg_camera = (Button) inflate.findViewById(R.id.btn_userimg_camera);
        btn_userimg_album = (Button) inflate.findViewById(R.id.btn_userimg_album);
        btn_userimg_cancel = (Button) inflate.findViewById(R.id.btn_userimg_cancel);

        btn_userimg_camera.setOnClickListener(this);
        btn_userimg_album.setOnClickListener(this);
        btn_userimg_cancel.setOnClickListener(this);

        dialog_camera.setContentView(inflate);
        Window dialogWindow = dialog_camera.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;
        lp.width = (int) getResources().getDisplayMetrics().widthPixels - 30; // 宽度
        dialogWindow.setAttributes(lp);
    }

    /**
     * 性别选择器初始化
     */
    private void initSexPicker() {
        cardSexItem.add(new CardBean(0, "女"));
        cardSexItem.add(new CardBean(1, "男"));

        pvCustomOptions_sex = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                getUpdateSex(options1 + "");
            }
        })
                .isDialog(false)
                .build();
        pvCustomOptions_sex.setPicker(cardSexItem);//添加数据

    }

    /**
     * 体重选择器初始化
     */
    private void initWeightPicker() {
        for (int i = 0; i < 100; i++) {
            cardWeightItem.add(new CardBean(i, "" + i));
        }
        pvCustomOptions_weight = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                getUpdateWeight(options1 + "");
            }
        })
                .isDialog(false)
                .build();
        pvCustomOptions_weight.setPicker(cardWeightItem);//添加数据

    }

    /**
     * 身高选择器初始化
     */
    private void initHeightPicker() {
        for (int i = 0; i < 100; i++) {
            cardHeightItem.add(new CardBean(i, "" + i));
        }
        pvCustomOptions_height = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                getUpdateHeight(options1 + "");
            }
        })
                .isDialog(false)
                .build();
        pvCustomOptions_height.setPicker(cardHeightItem);//添加数据
    }

    private void getUpdateSex(String s) {
        showLoading();
        Map<String, String> formMap = new HashMap<>();
        formMap.put(HttpKey.UPDATE_WA_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.UPDATE_WA_id, babyID);
        formMap.put(HttpKey.UPDATE_WA_nickName, "");
        formMap.put(HttpKey.UPDATE_WA_sex, s);
        formMap.put(HttpKey.UPDATE_WA_weight, "");
        formMap.put(HttpKey.UPDATE_WA_height, "");
        formMap.put(HttpKey.UPDATE_WA_birthtime, "");
        formMap.put(HttpKey.UPDATE_WA_constellation, "");
        formMap.put(HttpKey.UPDATE_WA_describe, "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.UPDATE_USERBADY_MSG, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        Wa_BabyMSG_Bean wa_babyMSG_bean = new Gson().fromJson(response, Wa_BabyMSG_Bean.class);
                        textView_wa_msg_sex.setText(wa_babyMSG_bean.getUserBaby().getSex().equals("1") ? "男" : "女");
                    }
                    ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    hideLoading();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //修改日期
    private void getUpdateBirthday(final String s) {
        showLoading();
        Map<String, String> formMap = new HashMap<>();
        formMap.put(HttpKey.UPDATE_WA_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.UPDATE_WA_id, babyID);
        formMap.put(HttpKey.UPDATE_WA_nickName, "");
        formMap.put(HttpKey.UPDATE_WA_sex, "");
        formMap.put(HttpKey.UPDATE_WA_weight, "");
        formMap.put(HttpKey.UPDATE_WA_height, "");
        formMap.put(HttpKey.UPDATE_WA_birthtime, s);
        formMap.put(HttpKey.UPDATE_WA_constellation, "");
        formMap.put(HttpKey.UPDATE_WA_describe, "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.UPDATE_USERBADY_MSG, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        Wa_BabyMSG_Bean wa_babyMSG_bean = new Gson().fromJson(response, Wa_BabyMSG_Bean.class);
                        String newStr = wa_babyMSG_bean.getUserBaby().getBirthtime()
                                .substring(6, wa_babyMSG_bean.getUserBaby().getBirthtime().length() - 2);
                        Long datatime = Long.valueOf(newStr);
                        textView_wa_msg_birthday.setText(getFormatedDateTime("yyyy-MM-dd", datatime));

                        ForPreference.putBoolean(ForContents.WA_BIRTHDAY_BOOL, true);

                        String[] mTimeSplit = s.split("-");
                        getUpdateConstellation(getAstro(Integer.parseInt(mTimeSplit[1]), Integer.parseInt(mTimeSplit[2])));
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //获取星座
    private String getAstro(int month, int day) {
//        String[] astro = new String[]{"摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座",
//                "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座"};
//        int[] arr = new int[]{20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22};// 两个星座分割日
//        int index = month;
//        // 所查询日期在分割日之前，索引-1，否则不变
//        if (day < arr[month - 1]) {
//            index = index - 1;
//        }
//        // 返回索引指向的星座string
//        return astro[index];

        return XingZuo.getXingZuoName(month, day);
    }

    //修改星座
    private void getUpdateConstellation(String s) {
        Map<String, String> formMap = new HashMap<>();
        formMap.put(HttpKey.UPDATE_WA_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.UPDATE_WA_id, babyID);
        formMap.put(HttpKey.UPDATE_WA_nickName, "");
        formMap.put(HttpKey.UPDATE_WA_sex, "");
        formMap.put(HttpKey.UPDATE_WA_weight, "");
        formMap.put(HttpKey.UPDATE_WA_height, "");
        formMap.put(HttpKey.UPDATE_WA_birthtime, "");
        formMap.put(HttpKey.UPDATE_WA_constellation, s);
        formMap.put(HttpKey.UPDATE_WA_describe, "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.UPDATE_USERBADY_MSG, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        Wa_BabyMSG_Bean wa_babyMSG_bean = new Gson().fromJson(response, Wa_BabyMSG_Bean.class);
                        textView_wa_msg_xingzuo.setText(wa_babyMSG_bean.getUserBaby().getConstellation());
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                    hideLoading();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getUpdateWeight(String s) {
        showLoading();
        Map<String, String> formMap = new HashMap<>();
        formMap.put(HttpKey.UPDATE_WA_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.UPDATE_WA_id, babyID);
        formMap.put(HttpKey.UPDATE_WA_nickName, "");
        formMap.put(HttpKey.UPDATE_WA_sex, "");
        formMap.put(HttpKey.UPDATE_WA_weight, s);
        formMap.put(HttpKey.UPDATE_WA_height, "");
        formMap.put(HttpKey.UPDATE_WA_birthtime, "");
        formMap.put(HttpKey.UPDATE_WA_constellation, "");
        formMap.put(HttpKey.UPDATE_WA_describe, "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.UPDATE_USERBADY_MSG, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        Wa_BabyMSG_Bean wa_babyMSG_bean = new Gson().fromJson(response, Wa_BabyMSG_Bean.class);
                        textView_wa_msg_weight.setText(wa_babyMSG_bean.getUserBaby().getWeight() + "kg");
                        ForPreference.putString(ForContents.WA_weight, wa_babyMSG_bean.getUserBaby().getWeight() + "");
                    }
                    ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    hideLoading();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getUpdateHeight(String s) {
        showLoading();
        Map<String, String> formMap = new HashMap<>();
        formMap.put(HttpKey.UPDATE_WA_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.UPDATE_WA_id, babyID);
        formMap.put(HttpKey.UPDATE_WA_nickName, "");
        formMap.put(HttpKey.UPDATE_WA_sex, "");
        formMap.put(HttpKey.UPDATE_WA_weight, "");
        formMap.put(HttpKey.UPDATE_WA_height, s);
        formMap.put(HttpKey.UPDATE_WA_birthtime, "");
        formMap.put(HttpKey.UPDATE_WA_constellation, "");
        formMap.put(HttpKey.UPDATE_WA_describe, "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.UPDATE_USERBADY_MSG, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        Wa_BabyMSG_Bean wa_babyMSG_bean = new Gson().fromJson(response, Wa_BabyMSG_Bean.class);
                        textView_wa_msg_height.setText(wa_babyMSG_bean.getUserBaby().getHeight() + "cm");
                        ForPreference.putString(ForContents.WA_heigh, wa_babyMSG_bean.getUserBaby().getHeight() + "");
                    }
                    ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    hideLoading();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    class CardBean implements IPickerViewData {
        int id;
        String cardNo;

        public CardBean(int id, String cardNo) {
            this.id = id;
            this.cardNo = cardNo;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getCardNo() {
            return cardNo;
        }

        public void setCardNo(String cardNo) {
            this.cardNo = cardNo;
        }

        @Override
        public String getPickerViewText() {
            return cardNo;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        textView_wa_msg_name.setText(ForPreference.getString(ForContents.WA_nickname));
        textView_wa_msg_jianjie.setText(ForPreference.getString(ForContents.WA_describe));

        wa_babyMSG_bean.getUserBaby().setNickName(ForPreference.getString(ForContents.WA_nickname));
    }

}
